#!/usr/bin/env python
# coding:utf-8

import sys
sys.path.append("..")

import webbrowser
from weibo import *  
from wb_parser import parse
from execute import execute
from symbol_table import symbol_table


APP_KEY = '3393803453'  
APP_SECRET = 'c0493aec3a795f02d2ea28a20f27f363'  

CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
  
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)  
url =  client.get_authorize_url()


print "If you redirect to https://api.weibo.com/oauth2/default.html?code=[code]"
print "Please input the [code] here\n"
raw_input("Press enter to continue ...")


webbrowser.open(url)

r = client.request_access_token(raw_input("input code:").strip())
client.set_access_token(r.access_token, r.expires_in)  

uid = client.account.get_uid.get()["uid"]
symbol_table.uid = uid



def show(result):
    if result['state']:
        if result['return_type'] == 'weibo':
            for w in result['result']:
                try:
                    print w['text'], w['id']
                except Exception, e:
                    # Some encoding error may be caught here
                    print 'encoding error ><'
                    continue

        elif result['return_type'] == 'comment':
            for c in result['result']:
                try:
                    print c['text'], c['id']
                except Exception, e:
                    print 'encoding error ><'
                    continue
        elif result['return_type'] == 'user':
            for w in result['result']:
                try:
                    print c['screen_name'], c['id']
                except Exception, e:
                    print 'encoding error ><'
                    continue
    else:
        print 'Execution fail'

while True:
    input_string = raw_input('> ')
    if input_string == '':
        break
    parse_info = parse(input_string)
    if parse_info['cmd'] != 'exception':
        result = execute(client, parse_info)
        show(result)
    else:
        'Error in parsing'
